package vashion.azeroth.core.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vashion.azeroth.contant.AddressErrorEnum;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.core.manager.personal.PersonalAddressManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.core.personal.pojo.PersonalAddress;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.PersonalAddressService;

import java.util.ArrayList;
import java.util.Date;

@Service
public class PersonalAddressServiceImpl<T> implements PersonalAddressService<T> {

	@Autowired
	private PersonalAddressManager personalAddressManager;

	@Autowired
	private PersonalMemberManager personalMemberManager;

	public ApiResult<PersonalAddress> addAddr(PersonalAddress address) {
		ApiResult<PersonalAddress> result = new ApiResult<PersonalAddress>();

		address.setTimeAdd(new Date(System.currentTimeMillis()));
		address.setTimeEdit(new Date(System.currentTimeMillis()));
		address.setStatus(1);

		try {

			PersonalMember personalMember = personalMemberManager.get(address
					.getMemberId());
			address.setMemberName(personalMember.getMemberName());
			ArrayList<PersonalAddress> myDefAddrList = personalAddressManager
					.getAddrList(address);

			// 会员未添加过收货地地址，（会员无有效收货地址），直接插入
			if (myDefAddrList.size() == 0) {
				address.setIsDelfault(1);
				PersonalAddress addNewDefAddr = personalAddressManager
						.save(address);
				result = ApiResult.newSuccessResult(addNewDefAddr);
				if (addNewDefAddr != null) {
					return result;
				}
			}

			//供应商只能上传一个取货地址
			if (AzerothConstants.PersonalMember.MemberType.supplier == personalMember.getType() 
					&& myDefAddrList.size() >= 1) {
				return ApiResult.newErrorResult(
						AddressErrorEnum.SUPPLIER_ADDR_OVER_COUNT.getErrorCode(),
						AddressErrorEnum.SUPPLIER_ADDR_OVER_COUNT.getErrorMessage());
			}

			if (myDefAddrList.size() >= 10) {
				return ApiResult.newErrorResult(
						AddressErrorEnum.ADDR_OVER_COUNT.getErrorCode(),
						AddressErrorEnum.ADDR_OVER_COUNT.getErrorMessage());
			}

			if (address.getIsDelfault() == 0) {
				PersonalAddress addNewDefAddr = personalAddressManager
						.save(address);
				result = ApiResult.newSuccessResult(addNewDefAddr);
				return result;
			}

			if (address.getIsDelfault() == 1) {
				long myDefAddrId = 0;
				for (int i = 0; i < myDefAddrList.size(); i++) {
					if (myDefAddrList.get(i).getIsDelfault() == 1) {
						myDefAddrId = myDefAddrList.get(i).getAddressId();
						
						// 旧的收货地址更新为非默认, 判断更新成功
						myDefAddrList.get(i).setIsDelfault(0);
						int updRes = personalAddressManager.update(myDefAddrList.get(i));
						if (updRes == 1) {
							continue;
						}else {
							return ApiResult.newErrorResult(AddressErrorEnum.UPDATE_DEFAULT_FAILED.getErrorCode(), AddressErrorEnum.UPDATE_DEFAULT_FAILED.getErrorMessage());
						}
					}
					continue;
				}

				// 原来无默认收货地址，新增默认收货地址
				if (myDefAddrId == 0) {
					address.setIsDelfault(1);
					address.setStatus(1);
					PersonalAddress addNewDefAddr = personalAddressManager
							.save(address);
					result = ApiResult.newSuccessResult(addNewDefAddr);
					if (addNewDefAddr != null) {
						return result;
					}
				} else {

//					// myDefAddrId.setIsDelfault(0);
//					// 旧的收货地址更新为非默认
//					PersonalAddress oldDefAddr = new PersonalAddress();
//					oldDefAddr.setAddressId(myDefAddrId);
//					oldDefAddr.setIsDelfault(0);
////					PersonalAddress updDefAddr = personalAddressManager
////							.update(oldDefAddr);
//					
//                     /**
//					 * 更新成功需要增加判断
//					 */
//					personalAddressManager.update(oldDefAddr);

					// 设置新增加的收货地址为默认
					address.setStatus(1);

					PersonalAddress addNewDefAddr = personalAddressManager
							.save(address);
					result = ApiResult.newSuccessResult(addNewDefAddr);
					return result;
				}
			} else {
				return ApiResult.newErrorResult(
						AddressErrorEnum.ADDR_SET_DEFAULT_ERROR.getErrorCode(),
						AddressErrorEnum.ADDR_SET_DEFAULT_ERROR
								.getErrorMessage());
			}
		} catch (Exception e) {
			return ApiResult.newErrorResult(
					AddressErrorEnum.ADDR_ADD_FAIL.getErrorCode(),
					AddressErrorEnum.ADDR_ADD_FAIL.getErrorMessage());
		}
		return result;
	}

	/**
	 * msgid=0 获取收货地址成功 msgid=1 用户名未传入 msgid=2 传入用户未设置收货地址或者收货地址为空 msgid=3
	 * 获取用户收货地址失败
	 * 
	 * */

	@SuppressWarnings("unchecked")
	public ApiResult<PersonalAddress> getAddrList(PersonalAddress address) {
		ApiResult<T> result = new ApiResult<T>();
		try {
			address.setStatus(1);
			ArrayList<PersonalAddress> addrList = personalAddressManager
					.getAddrList(address);
			if (addrList.size() == 0 || addrList == null) {
				return ApiResult.newErrorResult(
						GenericErrorEnum.QUERY_NO_DATA.getErrorCode(),
						GenericErrorEnum.QUERY_NO_DATA.getErrorMessage());
			} else {
				result = (ApiResult<T>) ApiResult.newSuccessResult(addrList);
				//添加地址总数量
				result.setTotalCount(personalAddressManager.getMyAddrCount(address.getMemberId()));
			}
		} catch (Exception e) {
			return ApiResult.newErrorResult(
					AddressErrorEnum.ADDR_GET_FAIL.getErrorCode(),
					AddressErrorEnum.ADDR_GET_FAIL.getErrorMessage());
		}
		return (ApiResult<PersonalAddress>) result;
	}

	/**
	 * msgid=0 删除收货地址成功 msgid=1 未传入地址id，请指定需要删除的地址id msgid=2 要删除的地址id不存在，pls
	 * check it msgid=1 删除收货地址失败
	 * 
	 * */

	public ApiResult<PersonalAddress> removeAddrByAddressId(
			PersonalAddress address) {
		// LogFactory log = (LogFactory)
		// LogFactory.getLog(PersonalAddressManager.class);
		try {
			int addrCount = personalAddressManager.getAddrById(address);
			if (addrCount == 0) {
				return ApiResult.newErrorResult(
						AddressErrorEnum.ADDR_ID_NOTEXIST.getErrorCode(),
						AddressErrorEnum.ADDR_ID_NOTEXIST.getErrorMessage());
			} else {
				address.setTimeEdit(new Date(System.currentTimeMillis()));
				int removeCode = personalAddressManager
						.removeAddrByAddressId(address);
				if (removeCode == 1) {
					return ApiResult.newSuccessResult();
				} else {
					return ApiResult.newErrorResult(
							AddressErrorEnum.ADDR_DEL_FAIL.getErrorCode(),
							AddressErrorEnum.ADDR_DEL_FAIL.getErrorMessage());
				}
			}
		} catch (Exception e) {
			return ApiResult.newErrorResult(
					AddressErrorEnum.ADDR_DEL_FAIL.getErrorCode(),
					AddressErrorEnum.ADDR_DEL_FAIL.getErrorMessage());
		}
	}

	public ApiResult<PersonalAddress> updAddr(PersonalAddress addr) {
		ApiResult<PersonalAddress> result = new ApiResult<PersonalAddress>();
		try {
			addr.setTimeEdit(new Date(System.currentTimeMillis()));

			long defAddrId = 0;
			if (addr.getIsDelfault() == 1) {
				// 获取默认的addrId
				defAddrId = personalAddressManager.getMyDefAddrId(addr
						.getMemberId());

				if (defAddrId > 0) {

					PersonalAddress oldDefAddress = new PersonalAddress();
					oldDefAddress.setIsDelfault(0);
					oldDefAddress.setAddressId(defAddrId);

//					更新默认收货地址为非默认
					int updateOldDefAddrRes = personalAddressManager
							.update(oldDefAddress);
					if (updateOldDefAddrRes == 1) {
						;
					} else {
						return ApiResult.newErrorResult(
								AddressErrorEnum.DELETE_DEFAULT_FAILED
										.getErrorCode(),
								AddressErrorEnum.DELETE_DEFAULT_FAILED
										.getErrorMessage());
					}

				}
			}
			int updateNewDefAddr = personalAddressManager.update(addr);
			if (updateNewDefAddr == 1) {
				result = ApiResult.newSuccessResult(addr);
			} else {
				result = ApiResult.newErrorResult(
						AddressErrorEnum.UPDATE_ADDR_FAIL.getErrorCode(),
						AddressErrorEnum.UPDATE_ADDR_FAIL.getErrorMessage());
			}
		} catch (Exception e) {
			ApiResult.newErrorResult(
					AddressErrorEnum.UPDATE_ADDR_FAIL.getErrorCode(),
					AddressErrorEnum.UPDATE_ADDR_FAIL.getErrorMessage());
		}
		return result;
	}

	@Override
	public ApiResult<PersonalAddress> queryDefaultAddress(PersonalAddress address) {
		ApiResult<PersonalAddress> result = new ApiResult<PersonalAddress>();
		try {
			address.setStatus(AzerothConstants.PersonalAddrss.PersonalAddressStatus.enable);
//			PersonalAddress defAddr = personalAddressManager.getMyDefAddr(address.getMemberId());
			ArrayList<PersonalAddress> defAddr = personalAddressManager.getAddrList(address);
			
			for (int i = 0; i < defAddr.size(); i++) {
				if (defAddr.get(i).getStatus() == 1 && defAddr.get(i).getIsDelfault() == 1) {
					result = ApiResult.newSuccessResult(defAddr.get(i));
				}else {
					continue;
				}
			}
//			if (null == defAddr) {
//				return ApiResult.newErrorResult(
//						GenericErrorEnum.QUERY_NO_DATA.getErrorCode(),
//						GenericErrorEnum.QUERY_NO_DATA.getErrorMessage());
//			} else {
//				result = ApiResult.newSuccessResult(defAddr);
//			}
		} catch (Exception e) {
			return ApiResult.newErrorResult(
					AddressErrorEnum.ADDR_GET_FAIL.getErrorCode(),
					AddressErrorEnum.ADDR_GET_FAIL.getErrorMessage());
		}
		return result;
	}

}
